package com.ghc.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * 定义全局过滤器， 会对所有路由生效
 */
@Slf4j
@Component  //让容器扫描到
public class BlackListFilter implements GlobalFilter, Ordered {

    // 模拟黑名单
    private static List<String> blackList = new ArrayList<>();

    static {
        //本机地址
//        blackList.add("0:0:0:0:0:0:0:1");
    }

    /**
     * 过滤器核心方法
     * @param exchange 封装了request、response对象上下文
     * @param chain 网关过滤器 （包含全局过滤器和单路由过滤器）
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //思路： 获取客户端ip， 判断是否在黑名单中， 在的话就拒绝访问， 不在的话就放行
        //从上下文中取出request、response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String clientIp = request.getRemoteAddress().getHostString();
        if (blackList.contains(clientIp)){
            //拒绝访问， 返回
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            log.debug("===>IP,{}  在黑名单中 ， 将拒绝访问", clientIp);
            String date = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(date.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
